package com.datuo.dtf.admin.service;

import com.datuo.dtf.admin.util.JwtTokenUtils;
import com.datuo.dtf.common.exception.BaseServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service
public class AuthService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 登录
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    public String login(String userName, String password){
        String token = null;
        //密码需要客户端加密后传递
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
        try {
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = JwtTokenUtils.generateToken(userDetailsService.loadUserByUsername(userName));
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
            BaseServiceException.assertError(true,"用户名或密码错误!");
        }
        return token;
    }

    /**
     * 刷新Token
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        if (!StringUtils.isEmpty(token) && !JwtTokenUtils.isTokenExpired(token)) {
            return JwtTokenUtils.refreshToken(token);
        }
        return null;
    }
}
